package com.example.roam.ui.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.roam.R;
import com.example.roam.api.Api;
import com.example.roam.game.util.GameConstant;
import com.example.roam.model.gson.PersonPassword;
import com.example.roam.model.gson.UpdatePassword;
import com.example.roam.model.gson.UpdateUser;
import com.example.roam.model.gson.User;
import com.example.roam.model.gson.Verify;
import com.example.roam.utils.Constans;
import com.example.roam.utils.HttpUtil;
import com.example.roam.utils.Md5Util;
import com.example.roam.utils.StatusBarUtils;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Iterator;

import kotlin.Pair;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class PersonalInformationActivity extends AppCompatActivity  {
    // 193331625bdfe3a8ecd00e634a39d56a
    private ImageView back;
    private ShapeableImageView img_head;
    private TextView txt_username , txt_eamail,txt_password;
    private String name;//用户昵称
    private RelativeLayout spirit, character , yx , mima ,updateInformation ;
    private int head_select;
    private static final String TAG = "PersonalInformationActi";
    private View updateInformationYx;
    private View updateInformationPassword;
    private Button btn_send_yzm,btn_send_yzm_certain,btn_send_email_certain ,btn_send_name_certain;
    private EditText edt_new_password,edt_old_password,edt_yzm_update,edt_new_name;
    private AlertDialog alertUpdatePassword;
    private Retrofit retrofit;
    private String newPassword;
    private AlertDialog alertUpdateName;
    private Retrofit retrofitEmail;
    private String emailCookie;
    private long sendEmailTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_information);
        StatusBarUtils.setWindowStatusBarColor(this, R.color.purple_500);//设置状态栏颜色为银白色

        name = Constans.u_username;
        head_select = Constans.head_select;
        iniView();
        iniData();
        iniEvent();
    }

    public void iniView() {
        back = this.findViewById(R.id.img_back);
        img_head = this.findViewById(R.id.img_head);
        txt_username = this.findViewById(R.id.txt_username);
        txt_eamail = this.findViewById(R.id.txt_email);
        txt_password = this.findViewById(R.id.txt_password);
        yx = this.findViewById(R.id.yx);
        mima = this.findViewById(R.id.mima);
        spirit = this.findViewById(R.id.spirit);
        character = this.findViewById(R.id.character);
//        updateInformation = this.findViewById(R.id.updateInformation);
        updateInformationPassword = LayoutInflater.from(this).inflate(R.layout.item_update_information_password,null,false);
        retrofit = new Retrofit.Builder().baseUrl(HttpUtil.ADDRESS).addConverterFactory(GsonConverterFactory.create()).build();
        retrofitEmail = new Retrofit.Builder().baseUrl(HttpUtil.EMAIL_ADDRESS+"/").addConverterFactory(GsonConverterFactory.create()).build();

    }

    public void iniData() {
        txt_username.setText(name);
        txt_eamail.setText(Constans.u_account);
//        txt_password.setText(Constans.u_password);
        txt_username.setText(Constans.u_username);
        Glide.with(this).load(Constans.u_head).into(img_head);
    }

    public void iniEvent() {
        MyListener myListener = new MyListener();
        back.setOnClickListener(myListener);
        spirit.setOnClickListener(myListener);
        character.setOnClickListener(myListener);
        mima.setOnClickListener(myListener);
        yx.setOnClickListener(myListener);
        txt_username.setOnClickListener(myListener);
//        updateInformation.setOnClickListener(myListener);
        img_head.setOnClickListener(myListener);
    }

    class MyListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.yx:

                    break;
                case R.id.mima:  // 点击密码事件
                    updateInformationPassword = LayoutInflater.from(PersonalInformationActivity.this).inflate(R.layout.item_update_information_password,null,false);
                    edt_yzm_update = updateInformationPassword.findViewById(R.id.edt_yzm_update);
                    btn_send_yzm = updateInformationPassword.findViewById(R.id.btn_send_yzm);
                    btn_send_yzm_certain = updateInformationPassword.findViewById(R.id.btn_send_yzm_certain);
                    edt_new_password = updateInformationPassword.findViewById(R.id.edt_new_password);
                    btn_send_yzm.setOnClickListener(this);  //发送验证码
                    btn_send_yzm_certain.setOnClickListener(this);
                    alertUpdatePassword = new AlertDialog.Builder(PersonalInformationActivity.this)
                            .setView(updateInformationPassword)
                            .create();
                    alertUpdatePassword.show();
                    break;
                case R.id.txt_username:
                    LayoutInflater layoutInflater = PersonalInformationActivity.this.getLayoutInflater();
                    View item = layoutInflater.inflate(R.layout.item_updater_person_information, null, false);
                    edt_new_name = item.findViewById(R.id.edt_new_name);
                    edt_new_name.setHint(Constans.u_username);
                    btn_send_name_certain = item.findViewById(R.id.btn_send_name_certain);
                    alertUpdateName = new AlertDialog.Builder(PersonalInformationActivity.this)
                            .setView(item)
                            .create();
                    alertUpdateName.show();
                    btn_send_name_certain.setOnClickListener(this);
                    iniData();
                    break;
                case R.id.spirit:
                    Intent intent1 = new Intent(PersonalInformationActivity.this,SpiritActivity.class);
                    intent1.putExtra("isUpdate",true);
                    startActivity(intent1);
                    break;
                case R.id.character:
                    Intent intent2 = new Intent(PersonalInformationActivity.this,InformationActivity.class);
                    intent2.putExtra("isUpdate",true);
                    startActivity(intent2);
                    break;
                case R.id.img_back:
                    PersonalInformationActivity.this.finish();
                    break;
//                case R.id.updateInformation:
//
//                    break;
                case R.id.btn_send_yzm:
                    newPassword = edt_new_password.getText().toString().trim();
                    if (!TextUtils.isEmpty(newPassword)  ) {
                        if( newPassword.length() >= 6 ) {
                            sendEmailPattern();
                            wait2SendEmail();
                        }else {
                            Toast.makeText(PersonalInformationActivity.this,"密码不能小于6位",Toast.LENGTH_SHORT).show();
                        }
                    }else {
                        Toast.makeText(PersonalInformationActivity.this,"密码不能为空",Toast.LENGTH_SHORT).show();
                    }
                    break;
                case R.id.btn_send_yzm_certain:
                    updateUserPasswordCertain(edt_yzm_update.getText().toString().trim());
                    alertUpdatePassword.dismiss();
                    break;
                case R.id.btn_send_email_certain:
                    Log.i(TAG, "onClick: send_email_certain");
                // nameundefind@163.com 123123
                    break;
                case R.id.btn_send_name_certain:
                    String newName = edt_new_name.getText().toString();
                    if(!TextUtils.isEmpty(newName)) {
                        retrofit = new Retrofit.Builder().baseUrl(HttpUtil.ADDRESS).addConverterFactory(GsonConverterFactory.create()).build();
                        retrofit.create(Api.class)
                                .updateUser(Constans.u_id,newName, Constans.u_password, Constans.u_character, Constans.u_spirit, Constans.u_head, Constans.character_select, Constans.spirit_select, Constans.head_select, HttpUtil.COOKIE)
                                .enqueue(new retrofit2.Callback<ResponseBody>() {
                                    @Override
                                    public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                                        if(response.code() == HttpURLConnection.HTTP_OK  ){
                                            Toast.makeText(PersonalInformationActivity.this,"修改成功！",Toast.LENGTH_SHORT).show();
                                            Constans.u_username = newName.trim();
                                            iniData();

                                        }else {
                                            Toast.makeText(PersonalInformationActivity.this,"修改失败", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                    @Override
                                    public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
                                        Toast.makeText(PersonalInformationActivity.this,"修改失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                    }else {
                        Toast.makeText(PersonalInformationActivity.this,"用户名不能为空", Toast.LENGTH_SHORT).show();
                    }
                    alertUpdateName.dismiss();
                    break;

                /** 搜索事件，输入后点击键盘搜索  */
//                edtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//                    @Override
//                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//                        if( actionId == EditorInfo.IME_ACTION_SEARCH ){
//                            doSearch();
//                        }
//                        return false;
//                    }
//                });

                case R.id.img_head:
                    Intent intent3 = new Intent(PersonalInformationActivity.this,InformationHeadActivity.class);
                    intent3.putExtra("isUpdate",true);
                    startActivity(intent3);
                    break;
            }
        }
    }

    private void wait2SendEmail(){
        btn_send_yzm.setClickable(false);
        new Thread(new Runnable() {
            @Override
            public void run() {
                int costTime = 30;
                while (costTime > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    int finalCostTime = costTime;
                    costTime--;
                    PersonalInformationActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            btn_send_yzm.setText(finalCostTime +"s");

                        }
                    });
                }

                PersonalInformationActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        btn_send_yzm.setClickable(true);
                        btn_send_yzm.setText("发送验证码");
                    }
                });
            }
        }).start();
    }

    private void sendEmailPattern(){  // 发送验证码！
        retrofitEmail.create(Api.class).tomail(Constans.u_account,HttpUtil.COOKIE).enqueue(new retrofit2.Callback<ResponseBody>() {
            @Override
            public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
                Log.i(TAG, "onResponse: responseBody: "+response.body());
                if(response.code() == HttpURLConnection.HTTP_OK){
                    Toast.makeText(PersonalInformationActivity.this,"验证码已发送！",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
                Toast.makeText(PersonalInformationActivity.this,"发送失败，请稍后重试...",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void updateUserPasswordCertain(String yzm){
        Log.i(TAG, "updateUserPasswordCertain: yzm: "+yzm);
        //                       验证邮箱
        retrofitEmail.create(Api.class).toVerify(yzm,emailCookie).enqueue(new Callback<Verify>() {
            @Override
            public void onResponse(Call<Verify> call, Response<Verify> response) {
                if(response.code() == HttpURLConnection.HTTP_OK ){
                    if(response.body().isSuccess()) {
                        try {
                            newPassword = Md5Util.encodeByMd5(PersonalInformationActivity.this.newPassword+Constans.SALT);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        updatePassword(newPassword);
                    }else {
                        Toast.makeText(PersonalInformationActivity.this,"验证码错误！",Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(PersonalInformationActivity.this,"修改失败...",Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Verify> call, Throwable t) {
                Toast.makeText(PersonalInformationActivity.this,"修改失败...",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void updatePassword(String newPassword){
        retrofit.create(Api.class).updatePassword(newPassword,Constans.u_account,HttpUtil.COOKIE).enqueue(new retrofit2.Callback<UpdatePassword>() {
            @Override
            public void onResponse(retrofit2.Call<UpdatePassword> call, retrofit2.Response<UpdatePassword> response) {
                Log.i(TAG, "onResponse: responseBody: "+response.body());
                if (response.code() == HttpURLConnection.HTTP_OK) {
                    if(response.body().isSuccess()){
                        Toast.makeText(PersonalInformationActivity.this,"修改密码成功！",Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(retrofit2.Call<UpdatePassword> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        iniData();

        // 论坛bug修复
        /**
         *  游戏流程（退出，第四章）
         *  文本
         *  素材（徽章，箭头，加载）
         *
         * */
    }
}